<?php


namespace app\common\command;


use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use Workerman\Worker;
use app\workerman\Events;

class Websocket extends Command
{
    protected function configure()
    {
        $this->setName('Websocket')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addArgument('type', Argument::OPTIONAL, '使用守护模式请输入参数：d')
            ->setDescription('聊天系统websocket服务端');
    }

    protected function execute(Input $input, Output $output)
    {
        //获取标准输入
        global $argv;
        $action = trim($input->getArgument('action'));
        if (!in_array($action, ['start', 'stop', 'reload', 'restart', 'status'])) {
            $output->writeln("非法动作参数 {$action}, 希望得到 start|stop|restart|reload|status|connections .参数值！");
            exit(1);
        }

        //是否开启守护进程
        if (!empty($input->getArgument('type')) && $input->getArgument('type') == 'd') {
            $type   = '-d';
        } else {
            $type = '';
        }

        $argv[0] = 'Websocket'; //workerman 需要的文件名
        $argv[1] = $action; //workerman 需要的动作名
        $argv[2] = $type ? '-d' : ''; //workerman 需要的 是否开启守护进程bool
        array_pop($argv);
        $this->start();
    }

    //开启服务函数
    public function start()
    {
        $this->startRegister();
        $this->startGateWay();
        $this->startBusinessWorker();
        Worker::runAll();
    }

    //开启register
    public function startRegister()
    {
        new Register('text://0.0.0.0:1236');
    }

    //开启gateway
    public function startGateWay()
    {

        $gateway = new Gateway("websocket://0.0.0.0:8282");
        $gateway->name                 = 'Websocket_Gateway';
        $gateway->count                = 1;
        $gateway->lanIp                = '127.0.0.1';
        $gateway->startPort            = 2300;
        $gateway->pingInterval         = 30;
        $gateway->pingNotResponseLimit = 0;
        $gateway->pingData             = sendWsToWeb(100,'心跳检测请求','ping');
        $gateway->registerAddress      = '127.0.0.1:1236';
    }

    //开启business
    private function startBusinessWorker()
    {
        $worker                  = new BusinessWorker();
        $worker->name            = 'BusinessWorker';
        $worker->count           = 1;
        $worker->registerAddress = '127.0.0.1:1236';
        $worker->eventHandler    = Events::class;
    }
}